package com.ustcinfo.ishare.esCURD;

import com.ustcinfo.ishare.utils.ClassFieldsCollector;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Shinelon on 2017/12/26.
 * 封装 ES 查询的 更新操作
 */
public class ESUpdate {
    private static final Logger LOGGER = LoggerFactory.getLogger(ESUpdate.class);

    /**
     * 更新数据(一整条)
     * @param transportClient
     * @param object
     * @param indexName
     * @param type
     * @param id                    被更新数据的id
     * @throws IOException
     */
    public void updateES(TransportClient transportClient, Object object, String indexName, String type,String id) throws IOException {
        XContentBuilder doc = null;
        IndicesExistsRequest inExistsRequest = new IndicesExistsRequest(indexName);
        IndicesExistsResponse inExistsResponse = transportClient.admin().indices()
                .exists(inExistsRequest).actionGet();
        if (inExistsResponse.isExists()) {
            Map map = new ClassFieldsCollector().getFiledsInfo(object);
            transportClient.prepareIndex(indexName, type,id).setSource(map).execute().actionGet();
        } else {
            System.out.println("索引不存在！");
        }
        System.out.println("更新成功!");
    }

    /**
     * 批量更新文档
     * @param transportClient
     * @param map       包含更新文档及对应id
     * @param indexName
     * @param type
     * @throws IOException
     */
    public void updateESByBulk(TransportClient transportClient, Map<Object,String> map, String indexName, String type) throws IOException {
        BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
        Iterator keys = map.entrySet().iterator();
        while (keys.hasNext()) {
            Map.Entry entry = (Map.Entry) keys.next();
            Map newMap = new ClassFieldsCollector().getFiledsInfo(entry.getKey());
            bulkRequestBuilder.add(transportClient.prepareIndex(indexName,type,map.get(entry.getKey().toString())).setSource(newMap));
        }
        bulkRequestBuilder.execute().actionGet();
        System.out.println("批量更新文档成功！");
    }

    /**
     * 更新数据（更新一个字段）
     * @param transportClient
     * @param indexName
     * @param type
     * @param id
     * @param field
     * @param fieldValue
     */
    public void updateField(TransportClient transportClient,String indexName, String type,String id,String field,Object fieldValue) throws IOException {
        boolean isUpdate = transportClient.update(new UpdateRequest(indexName,type,id).doc(XContentFactory.jsonBuilder()
                .startObject().field(field,fieldValue).endObject())).actionGet().isFragment();
        if (!isUpdate){
            System.out.println("更新字段成功！");
        }else{
            System.out.println("更新字段失败！");
        }
    }

    /**
     * 更新多字段
     * @param transportClient
     * @param indexName
     * @param type
     * @param id
     * @param map
     * @throws IOException
     */
    public void updateMultiField(TransportClient transportClient,String indexName, String type,String id,Map<String,Object> map) throws IOException {
        boolean isUpdate = transportClient.update(new UpdateRequest(indexName,type,id).doc(map)).actionGet().isFragment();
        if (!isUpdate){
            System.out.println("更新多字段成功！");
        }else{
            System.out.println("更新多字段失败！");
        }
    }

}
